package com.lz.autotest.project.system.security.service;

import java.util.concurrent.TimeUnit;

import com.lz.autotest.common.constant.CacheConst;
import com.lz.autotest.common.utils.MD5Utils;
import com.lz.autotest.project.system.manager.AsyncManager;
import com.lz.autotest.project.system.manager.factory.AsyncFactory;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.lz.autotest.common.constant.CacheConstants;
import com.lz.autotest.common.constant.Constants;
import com.lz.autotest.common.exception.user.UserPasswordNotMatchException;
import com.lz.autotest.common.exception.user.UserPasswordRetryLimitExceedException;
import com.lz.autotest.common.utils.MessageUtils;
import com.lz.autotest.common.utils.SecurityUtils;
//import com.lz.pricing.framework.manager.AsyncManager;
//import com.lz.pricing.framework.manager.factory.AsyncFactory;
import com.lz.autotest.common.redis.RedisCache;
import com.lz.autotest.project.system.security.context.AuthenticationContextHolder;
import com.lz.autotest.project.system.domain.SysUser;

/**
 * 登录密码方法
 *
 * @author lz
 */
@Component
public class SysPasswordService
{
    @Autowired
    private RedisCache redisCache;

    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    @Value(value = "${user.password.lockTime}")
    private int lockTime;

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username)
    {
        return CacheConst.env+CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    public void validate(SysUser user)
    {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();

        Integer retryCount = redisCache.getCacheObject(getCacheKey(username));

        if (retryCount == null)
        {
            retryCount = 0;
        }

        if (retryCount >= Integer.valueOf(maxRetryCount).intValue())
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                    MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime)));
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }

        if (!matches(user, password))
        {
            retryCount = retryCount + 1;
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                    MessageUtils.message("user.password.retry.limit.count", retryCount)));
            redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new UserPasswordNotMatchException();
        }
        else
        {
            clearLoginRecordCache(username);
        }
    }

    /**
     * 前端的登录密码和数据库的密码进行比对。需要注意的时候，国君和定价平台1.0的密码加密和交易方法有所不同，所以需要做兼容性保护
     * @param  user 从数据库中获取的用户信息类，包含加密后的密码
     * @param  rawPassword 前端传的原始密码，如果是国君1.0的的，传的是MD5加密后的密码
     * @return  boolean  如果密码匹配，返回TRUE，否则返回FALSE;
     * @author lz at 2023.7.4
     *
     * */
    public boolean matches(SysUser user, String rawPassword)
    {
        // 国君1.0中，密码MD5加密，客户端传上来的密码就是加密过的，和数据库的密码可以直接比对
        if(rawPassword.length() > 15)
        {
            if(StringUtils.equalsIgnoreCase(rawPassword, user.getPassword()))
            {
                user.setPassword(SecurityUtils.encryptPassword(rawPassword));
                return  true;
            }
        }

        // 用新的密码校验方法
        boolean blMatch = SecurityUtils.matchesPassword(rawPassword, user.getPassword());
        if(blMatch)
        {
            return true;
        }

        // 再用国君老的MD5加密方法进行校验
        String md5Pwd =  MD5Utils.MD5(rawPassword);
        if(StringUtils.equalsIgnoreCase(md5Pwd, user.getPassword()))
        {
            // 设置密码
            user.setPassword(SecurityUtils.encryptPassword(rawPassword));
            return  true;
        }
        return false;
    }

    public void clearLoginRecordCache(String loginName)
    {
        if (redisCache.hasKey(getCacheKey(loginName)))
        {
            redisCache.deleteObject(getCacheKey(loginName));
        }
    }
}
